import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import qs from 'qs';
import styles from './index.less';
import { Card, Button, Tabs, DatePicker, Row, Checkbox, Col, Select, TreeSelect } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { BaseTable, utils } from '@/components/BaseTable';
import { getTitleTree, getFixedColumns } from './utils/tableUtils';
import AuthorizedButton from '@/components/AuthorizedButton';
import PageEmpty from '@/components/PageEmpty';

const { TabPane } = Tabs;
const { Option } = Select;
const months = [
  {
    title: '年度合计',
    value: '14',
    key: '14',
  },
  {
    title: '全部月份',
    value: '13',
    key: '13',
    children: [
      { key: '1', value: '1', title: '1月' },
      { key: '2', value: '2', title: '2月' },
      { key: '3', value: '3', title: '3月' },
      { key: '4', value: '4', title: '4月' },
      { key: '5', value: '5', title: '5月' },
      { key: '6', value: '6', title: '6月' },
      { key: '7', value: '7', title: '7月' },
      { key: '8', value: '8', title: '8月' },
      { key: '9', value: '9', title: '9月' },
      { key: '10', value: '10', title: '10月' },
      { key: '11', value: '11', title: '11月' },
      { key: '12', value: '12', title: '12月' },
    ],
  },
];
const SupplyAndMarketing = props => {
  const { dispatch, reduxItem } = props;
  const {
    overAllYears,
    currentYear,
    currentShowGroup,
    currentMonths,
    currentLevel,
    dataSource,
    expandedRowKeys,
  } = reduxItem;
  const [emptyMsg, setEmptyMsg] = useState('暂无数据');
  const [endTime, setEndTime] = useState(moment().format('YYYY-MM')); // 截至年月
  useEffect(() => {
    setEmptyMsg('数据加载中...');
    dispatch({
      type: 'SupplyMarketingAnalysis/requestData',
      payload: {
        params: {
          ofYearMonth: endTime,
          year: currentYear,
        },
      },
      callback: result => {
        if (!result.data.detailList) setEmptyMsg('暂无数据');
      },
    });
  }, [endTime, currentYear]);

  // 处理-------截止年月
  const handleDeadlineYearMonth = (field, value) => {
    // 改变截止年月
    setEndTime(value);
  };

  // 统一处理筛选的值
  const handlerChangeCurrentVal = (value, name) => {
    dispatch({
      type: 'SupplyMarketingAnalysis/changeCurrentVal',
      payload: {
        [name]: name === 'currentYear' ? parseInt(value, Number) : value,
      },
    });
  };

  const titleTree = getTitleTree(currentYear, currentMonths, currentShowGroup);
  const sessionToken = localStorage.getItem('sessionToken');
  const exportQueryString = qs.stringify({ yearMonth: endTime, sessionToken });
  return (
    <PageHeaderWrapper
      className={styles.SignPlanProgress}
      breadcrumb={null}
      title={<></>}
      extra={
        <>
          截止年月：
          <DatePicker.MonthPicker
            allowClear={false}
            onChange={handleDeadlineYearMonth}
            value={moment(endTime)}
            format="YYYY-MM"
            disabledDate={current => current && current > moment().endOf('day')}
          />
          &nbsp;&nbsp;
          <AuthorizedButton authority="Comprehensive_Export">
            <Button
              disabled={dataSource.length <= 0}
              className="yellow-button"
              target="_blank"
              href={`${process.env.apiUrl}/api/v1/report/dmAnalyticalExport?${exportQueryString}`}
            >
              导出报表
            </Button>
          </AuthorizedButton>
        </>
      }
    >
      <Card>
        {dataSource.length > 0 && expandedRowKeys.length > 0 ? (
          <>
            <Row align="middle" type="flex" justify="space-between">
              <Col>
                <span>显示：</span>
                <Select defaultValue="最新全盘动态" style={{ width: 120 }} size="small">
                  <Option value="region">最新全盘动态</Option>
                </Select>
                &nbsp;&nbsp;
                <Select
                  // mode="multiple"
                  size="small"
                  style={{ width: 140 }}
                  placeholder="请选择"
                  value={currentShowGroup}
                  onChange={value => handlerChangeCurrentVal(value, 'currentShowGroup')}
                >
                  <Option key="期初存货/新供/综合">期初存货/新供/综合</Option>
                  <Option key="期初存货">期初存货</Option>
                  <Option key="新供">新供</Option>
                  <Option key="综合">综合</Option>
                </Select>
                &nbsp;&nbsp;
                <Select
                  // mode="multiple"
                  size="small"
                  style={{ width: 100 }}
                  placeholder="请选择"
                  value={
                    new Date().getFullYear().toString() === currentYear.toString()
                      ? `${currentYear}(今年)`
                      : currentYear
                  }
                  onChange={value => handlerChangeCurrentVal(value, 'currentYear')}
                >
                  {overAllYears.map(data => (
                    <Option key={data}>{data}</Option>
                  ))}
                </Select>
                &nbsp;&nbsp;
                <TreeSelect
                  size="small"
                  style={{ width: 195 }}
                  value={currentMonths}
                  mode="multiple"
                  onChange={value => handlerChangeCurrentVal(value, 'currentMonths')}
                  treeCheckable
                  maxTagCount={2}
                  treeData={months}
                ></TreeSelect>
              </Col>
              <Col>
                层级：
                <Select
                  size="small"
                  value={currentLevel}
                  style={{ width: 120 }}
                  onChange={value => handlerChangeCurrentVal(value, 'currentLevel')}
                >
                  <Option value="region">区域</Option>
                  <Option value="cityCompany">城市公司</Option>
                  <Option value="project">项目</Option>
                  <Option value="stage">分期</Option>
                </Select>
              </Col>
            </Row>
            <BaseTable
              subtractHeight="180px"
              defaultExpandedRowKeys={expandedRowKeys}
              expandColumnKey="name"
              fixedColumns={getFixedColumns(titleTree, currentMonths, currentShowGroup)}
              headerHeight={[30, 30, 30, 30, 30]}
              headerRenderer={utils.getHeaderRenderer(titleTree, 4)}
              treeData={dataSource}
            />
          </>
        ) : (
          <PageEmpty emptyTitle={emptyMsg} />
        )}
      </Card>
    </PageHeaderWrapper>
  );
};

export default connect(state => ({
  reduxItem: state.SupplyMarketingAnalysis,
}))(SupplyAndMarketing);
